from numpy import *
from scipy.interpolate import griddata
from array import *
from math import *
import sys 
from ROOT import gROOT, TCanvas , TH2D, TFile, gStyle, TGraph2D

def is_int(s):
    try:
        int(s)
        return True
    except ValueError:
        return False

def is_float(s):
    try:
        float(s)
        return True
    except ValueError:
        return False
    
    
    

numbers_ok = True
for i in sys.argv[4:6] : 
    if i=='--help' :
        print 'usage : python Converter.py <Input file Ex> <Input file Ey> <Output file> <nx> <ny> <Lx> <Ly>\b'
    if is_int(i) == False : 
            numbers_ok = False
            
for i in sys.argv[6:8] :  
    if is_float(i) == False : 
            numbers_ok = False
    infileX = sys.argv[1]
    infileY = sys.argv[2]
    outfile = sys.argv[3]
    nx = int(sys.argv[4])
    ny = int(sys.argv[5])
    Lx = float(sys.argv[6])
    Ly = float(sys.argv[7])
     
    
    print 'Reading data file ' + infileX + ' and ' + infileY
    fX = open(infileX, "r")
    fY = open(infileY, "r")

if len(sys.argv)<8 or numbers_ok == False :
    print 'invalid number of arguments or wrong type of arguments \b'
    print 'usage : python Converter.py <Input file Ex> <Input file Ey> <Output file> <nx> <ny> <Lx> <Ly>\b'
    print 'where nx and ny are integers'
else : 
            
    print '[Converter] Reading data file ' + infileX + ' and ' + infileY
    print "[Converter] %d x %d grid, %5.1f x % 5.1f micron model, oufile is %s" %(nx,ny,Lx,Ly,outfile)


    linesx = fX.readlines();
    linesy = fY.readlines();

    xX = zeros(len(linesx), float)
    yX = zeros(len(linesx), float)
    xY = zeros(len(linesy), float)
    yY = zeros(len(linesy), float)   
    Ex = zeros(len(linesx), float)
    Ey = zeros(len(linesy), float)
  
    vX = []
    vY = []
    j = 0
    for i in linesx :
        thisline = i.split();
        xX[j] = (float(thisline[0]));
        yX[j] = (float(thisline[1]));
        Ex[j] = float(thisline[2]);
        vX.append([xX[j], yX[j]])
        j = j + 1
    
    j=0
    for i in linesy :
        thisline = i.split();
        xY[j] = (float(thisline[0]));
        yY[j] = (float(thisline[1]));
        Ey[j] = float(thisline[2]);
        vY.append([xY[j], yY[j]])
        j = j + 1   
    
    
    xminX = min(xX)
    yminX = min(yX)
    
    
    xminY = min(xY)
    yminY = min(yY)
    

    print "[Converter] Translation data to put lower left corner at x,y = (0,0) and volume in positive x and y axis \b"  
    for i in range(0,len(xX)) :
        vX[i][0]= xX[i]-xminX 
        vX[i][1]= yX[i]-yminX

    for i in range(0,len(xY)) :
        vY[i][0]= xY[i]-xminY 
        vY[i][1]= yY[i]-yminY 
           

    #gr = TGraph2D(len(vX),xX,yX,Ex)
    #gr.Draw("colz")
    
    
    print '[Converter] interpolating data and creating a regular grid of %d x %d , %5.1f x %5.1f microns \b' % (nx,ny,Lx,Ly) 
    grid_xX, grid_yX = mgrid[0:Lx:Lx/nx, 0:Ly:Ly/ny]
    grid_z0X = griddata(vX, Ex, (grid_xX, grid_yX), method='nearest')
    grid_z1X = griddata(vX, Ex, (grid_xX, grid_yX), method='linear')
    grid_z2X = griddata(vX, Ex, (grid_xX, grid_yX), method='cubic')

    #grid_z0X*=1e-4
    #grid_z1X*=1e-4
    #grid_z2X*=1e-4

    grid_xY, grid_yY = mgrid[0:Lx:Lx/nx, 0:Ly:Ly/ny]
    grid_z0Y = griddata(vY, Ey, (grid_xY, grid_yY), method='nearest')
    grid_z1Y = griddata(vY, Ey, (grid_xY, grid_yY), method='linear')
    grid_z2Y = griddata(vY, Ey, (grid_xY, grid_yY), method='cubic')
    
        
    #grid_z0Y*=1e-4
    #grid_z1Y*=1e-4
    #grid_z2Y*=1e-4   
    
#    f2 = open(outfile, "w")
#    print 'Writing outfile ' + outfile 
#    for ii in grid_x : 
#        j = 0
#        for jj in grid_y[0] : 
#            f2.write('{0} {1} {2} \n'.format(grid_x[i, j], grid_y[i, j], grid_z2[i, j]))
#            j = j + 1
#        i = i + 1
#    
#    
#    f2.close()
    fX.close()  
    fY.close()  

    
    x=0
    y=0
    E=0
    
    
    print "[Converter] Creating final data grid histograms \b"
    gStyle.SetPalette(1)
    hx = TH2D("hEx","hEx",nx,0,Lx,ny,0,Ly)
    hy = TH2D("hEy","hEy",nx,0,Lx,ny,0,Ly)
    i = 0
    j = 0
    for ii in grid_xX : 
        j = 0
        for jj in grid_yX[0] : 
            hx.SetBinContent(i,j,grid_z2X[i,j])
            hy.SetBinContent(i,j,grid_z2Y[i,j])
            j = j + 1
        i=i+1
    
    

    cX = TCanvas()
    hx.Draw("colz")
    cY = TCanvas()
    hy.Draw("colz")
    
    
    print "[Converter] Writing histogram to root file %s" % outfile
    
    f = TFile(outfile,"RECREATE")
    hx.Write()
    hy.Write()
    
    print "[Converter]saving histograms in png format \b"
    print "[Converter] Ex written in %s \b" % "Ex_"+outfile+".png"
    print "[Converter] Ey written in %s \b" % "Ey_"+outfile+".png"

    hx.SaveAs("Ex_"+outfile+".png")
    hy.SaveAs("Ey_"+outfile+".png")
    
    token = raw_input("finished ? press enter to quit \b")

